﻿using System;
using System.Collections.Generic;
using LogManager.Base;
using LogManager.Base.Data;
using LogManager.Windows.Data;
using System.Diagnostics.Eventing.Reader;

namespace LogManager.Windows
{
    public class WindowsLog : BaseLog, ILog
    {
        private IEventTypeService _typeService;
        private Lazy<IDictionary<string, object>> _properties;       

        public WindowsLog(IEventTypeService typeService)
        {
            _typeService = typeService;
        }

        public override void Initialize(string serverName, string logName, string typeId)
        {
            _properties = new Lazy<IDictionary<string, object>>(() => GetLogInformation(logName));
            ExportService  = new WindowsEventExportService(serverName, logName,_typeService);
            base.Initialize(serverName, logName, typeId);
        }

        public override IDictionary<string, object> Properties
        {
            get { return _properties.Value; }
        }

        #region Property Proxies

        public DateTime? CreationTime
        {
            get { return (DateTime?)Properties.GetValueOrDefault("CreationTime", null); }
        }

        public long? FileSize
        {
            get { return (long?)Properties.GetValueOrDefault("FileSize", null); }
        }

        public DateTime? LastAccessTime
        {
            get { return (DateTime?)Properties.GetValueOrDefault("LastAccessTime", null); }
        }

        public bool? IsLogFull
        {
            get { return (bool?)Properties.GetValueOrDefault("IsLogFull", null); }
        }

        #endregion

        /// <summary>
        /// Loads information about the log from the windows server.
        /// </summary>
        /// <param name="logName">Unique name of the log</param>
        /// <returns></returns>
        private IDictionary<string, object> GetLogInformation(string logName)
        {
            using (var session = new EventLogSession())
            {
                var info = session.GetLogInformation(logName, PathType.LogName);

                return new Dictionary<string, object>
                                  {
                                      {"LastWriteTime", info.LastWriteTime},
                                      {"RecordCount", info.RecordCount},
                                      {"CreationTime", info.CreationTime},
                                      {"FileSize", info.FileSize},
                                      {"IsLogFull", info.IsLogFull},
                                      {"LastAccessTime", info.LastAccessTime}
                                  };
            }
        }
    }
}
